package com.manjusaka.structure7.Flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * 享元模式--实现对象的复用
 * 将一个对象注册到一个map中，获取的方式是根据Key来获取
 * Created by manjusaka on 2017/7/6.
 */
public class FlyweightPattern {
    //单例
    private FlyweightPattern(){}
    private FlyweightPattern INSTANCE=new FlyweightPattern();
    public FlyweightPattern getInstance(){
        return INSTANCE;
    }
    //1---设计存储User的map  key--userId  value-User
    private static Map<Long,User> cache=new HashMap<Long,User>();

    public void registerUser(User user){
        cache.put(user.getId(),user);
    }

    public User getUser(long id){
        User user = cache.get(id);
        if(user==null){
            //数据库查询 然后put
        }
        return user;
    }
}

class User {
    private long id;
    private int age;
    private String name;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


